from services import BaseService
from tools.db_tool import DbTool
from decorators import Transactional
from mauth.login_user_holder import LoginUserHolder
from tools import generate_id


class SchemaGroupService(BaseService):
    """
    模型分组模块业务处理类
    """

    @Transactional()
    def save(self, form):
        """
        添加模型分组
        :param form:
        :return:
        """
        model = self.model(**form.data)
        DbTool.check_unique(self.model, "code", form.code.data, None, "唯一编码已存在")
        model.id = generate_id()
        model.createUser = LoginUserHolder.get_user_id()
        model.updateUser = LoginUserHolder.get_user_id()
        self.db.session.add(model)

    @Transactional()
    def update(self, form):
        """
        修改模型分组
        :param form:
        :return:
        """
        model = self.model(**form.data)
        DbTool.check_unique(
            self.model, "code", form.code.data, form.id.data, "唯一编码已存在"
        )
        model.updateUser = LoginUserHolder.get_user_id()

        self.db.session.query(self.model).filter_by(id=form.id.data).update(
            model.to_dict()
        )
